#ifndef CHARTPLOTTER_H
#define CHARTPLOTTER_H

#include "source/logger.h"
#include <QObject>
#include <QVector>
#include <QRunnable>
#include <QThreadPool>
#include <QtCharts>
#include <QQuickPaintedItem>
#include <QPainter>
#include <QPieSeries>

class ChartPlotter : public QQuickPaintedItem {
    Q_OBJECT
    Q_PROPERTY(QVector<QVector<int>> data READ data WRITE setData NOTIFY dataChanged)

public:
    static ChartPlotter& getInstance() {
        static ChartPlotter instance;
        return instance;
    }

    QVector<QVector<int>> data() const {
        return m_data;
    }

    void setData(const QVector<QVector<int>> &data) {
        m_data = data;
        emit dataChanged();
    }

    void paint(QPainter *painter) override;

    static QObject* qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine) {
        Q_UNUSED(engine)
        Q_UNUSED(scriptEngine)
        return &ChartPlotter::getInstance();
    }

public slots:
    void drawCharts(const QVector<QVector<int>> &data);

signals:
    void dataChanged();

private:
    QVector<QVector<int>> m_data;

    ChartPlotter(QQuickPaintedItem *parent = nullptr) : QQuickPaintedItem(parent) {
        QThreadPool::globalInstance()->setMaxThreadCount(5);
    }

    ~ChartPlotter() = default;

    ChartPlotter(const ChartPlotter&) = delete;
    ChartPlotter& operator=(const ChartPlotter&) = delete;

    void drawRingChart(QPainter *painter);
};

class ChartTask : public QRunnable {
public:
    ChartTask(ChartPlotter *plotter, const QVector<QVector<int>> &data) : m_plotter(plotter), m_data(data) {}

    void run() override {
        LogDebug << "Processing data in thread";
        QMetaObject::invokeMethod(m_plotter, [=] {
            m_plotter->update();
        });
    }

private:
    ChartPlotter *m_plotter;
    QVector<QVector<int>> m_data;
};

#endif // CHARTPLOTTER_H
